package eu.mvanco.lila;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Calendar;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import eu.mvanco.lila.settings.MyPrefsActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Main activity of application. Shows buttons to start and stop background service
 * and contains menu for settings. Starts background service BgService...
 * 
 * @author Matus
 *
 */
public class MainActivity extends Activity
{
	
	static final int GET_USERNAME_REQUEST = 1;  // The request code
	public static String SESSION_ID = "sessionID";
	Handler mHandler;
	
	private PendingIntent mAlarmSender;
	private Button registrationButton;
	private Button loginButton;
	private EditText username;
	private EditText password;
	
	final Runnable loginError = new Runnable() {
	    public void run() {
	    	Toast.makeText(MainActivity.this, "Wrong credentials or missing internet connection. Try again", Toast.LENGTH_LONG).show();
        	username.setText("");
        	password.setText("");
    	}
	};
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mHandler = new Handler(Looper.getMainLooper());
        
        // Create an IntentSender that will launch our service, to be scheduled
        // with the alarm manager.w
        mAlarmSender = PendingIntent.getService(MainActivity.this,
                0, new Intent(MainActivity.this, BgService.class), 0);
        
        setContentView(R.layout.login_screen);
        
        registrationButton = (Button) findViewById(R.id.registration_button);
        loginButton = (Button) findViewById(R.id.login_button);
        
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        
        registrationButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(MainActivity.this, RegistrationActivity.class);
				startActivityForResult(i, GET_USERNAME_REQUEST);
			}
        	
        });
        
        loginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			    new Thread(new Runnable() {
			        //Thread to stop network calls on the UI thread
			        public void run() {
						
						StringBuilder url = new StringBuilder();
						url.append("http://mvanco.eu/index.php/action/login");
						url.append("/" + username.getText().toString());
						url.append("/" + password.getText().toString());
						HttpGet getRequest = new HttpGet(url.toString());
						HttpClient httpclient = new DefaultHttpClient();
					    HttpResponse response = null;
			        	
						try {
							response = httpclient.execute(getRequest);
						} catch (ClientProtocolException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						if (response != null) {
							StatusLine statusLine = response.getStatusLine();

			                if (statusLine.getStatusCode() == 201) {
			                	Intent i = new Intent(MainActivity.this, UserPanelActivity.class);
			                	
			                	String content = null;
								try {
									content = convertStreamToString(response.getEntity().getContent());
								} catch (IllegalStateException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
			                	i.putExtra(SESSION_ID, content);
			                	
			                	startActivity(i);
			                	
			                }
			                else {
			                	mHandler.post(loginError);
			                }
			                
						}
						else {
							mHandler.post(loginError);
						}
		                
			        }
			    }).start();
				
			}
        	
        });

        // Watch for button clicks.
        //Button button = (Button)findViewById(R.id.start_alarm);
        //button.setOnClickListener(mStartAlarmListener);
        //button = (Button)findViewById(R.id.stop_alarm);
        //button.setOnClickListener(mStopAlarmListener);
    }
    
    public static String convertStreamToString(InputStream inputStream) throws IOException {
        if (inputStream != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),1024);
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                inputStream.close();
            }
            return writer.toString();
        } else {
            return "";
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Check which request we're responding to
        if (requestCode == GET_USERNAME_REQUEST) {
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
            	username.setText(data.getStringExtra(RegistrationActivity.USERNAME));
            	password.setText("");
            }
            else {
            	Toast.makeText(this, "Error during registration, try again with other values or check your internet connection.", Toast.LENGTH_LONG).show();
            }
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.action_settings:
            	//Toast.makeText(this, "mytext", Toast.LENGTH_LONG).show();
                startActivity(new Intent(MainActivity.this, MyPrefsActivity.class));
                return true;
            default:
                return false;
        }
    }
    
    
}
